<template>
	<view class="order-list" :class="themeName">
		<!-- Tabs -->
		<navbar title="订单列表"></navbar>
		<u-tabs :list="tabsList" :is-scroll="false" :height="80" :active-color="themeColor" :bar-style="{top: '100%'}"
			:current="tabsIndex" @change="changeCurrentTab" />

		<!-- Order Lists -->
		<view class="order-item">
			<mescroll-uni ref="mescrollRef" :fixed="false" :up="{
				  auto: false,
				  noMoreSize: 3,
				  empty: {
				  	icon: $getImageUri('resource/image/shopapi/uniapp/empty/order.png'),
				  	tip: $zhTran('暂无订单~'),
				  	fixed: true
				  }
			  }" :down="{ auto: false }" @init="mescrollInit" @down="downCallback" @up="upCallback">
				<block v-for="(tabItem, tabIndex) in tabsList" :key="tabItem['sign']">
					<view class="order-contain" v-if="currentTab['sign'] === tabItem['sign']">
						<view class="order" v-for="orderItem in tabsList[tabIndex].list" :key="orderItem.id">
							<!-- Order Header -->
							<view class="order-header">

								<template v-if="orderItem.pay_way === 8">
									<view class="order-tag order-tag--red">{{$zhTran('货到付款')}}</view>
								</template>
								<view class="order-sn">{{$zhTran('订单编号:')}}{{ orderItem.sn }}</view>
								<view :class="[
											'order-status', 
											`order-status--${orderStatus[orderItem.order_status]['style']}`
										]">{{ orderStatus[orderItem.order_status]['name'] }}</view>
							</view>

							<!-- Order Main -->
							<view class="order-main" @tap="goOrderDetail(orderItem.id)">
								<goods-card v-for="(goodsItem, goodsIndex) in orderItem.order_goods" :key="goodsIndex"
									shape="rectangle" :name="goodsItem.goods_name" :image="goodsItem.goods_image"
									:contain-style="{ 'border-raius': 0, 'height': '330rpx' }" :fieldShowHide="{
										show_cgp_tag:0
									}" :image-style="{ 'width': '180rpx', 'height': '180rpx' }">
									<view class="flex-1" slot="default">
										<view class="m-t-10 flex row-between">
											<price :content="goodsItem.goods_price" mainSize="32rpx" minorSize="24rpx"
												:prefix="price_symbol" color="rgba(250, 64, 52, 1)" />
											<text class="lighter sm">x{{ goodsItem.goods_num }}</text>
										</view>
									</view>
								</goods-card>
								<view class="order-desc" v-if="orderItem.integrate_amount > 0">
									<text>{{$zhTran('共 '+ orderItem.total_num +' 件商品,已付款:')}}</text>
									<price class="normal lg" :content="orderItem.done_amount" :prefix="price_symbol" />
									<text>{{$zhTran(',应付款:')}}</text>
									<price class="normal lg" :content="orderItem.integrate_amount"
										:prefix="price_symbol" />
								</view>
								<view class="order-desc" v-else>
									<text>{{$zhTran('共 '+orderItem.total_num+' 件商品,应付款:')}}</text>
									<price class="normal lg" :content="orderItem.order_amount" :prefix="price_symbol"
										color="rgba(250, 64, 52, 1)" />
								</view>
							</view>

							<!-- Order Footer -->
							<view class="order-footer" v-if="orderItem.buttons.length">
								<block v-for="buttonItem in orderItem.buttons" :key="buttonItem.event">
									<view :class="[
										'order-button', 
										`order-button--${buttonItem.style}`
										]" @tap="onOrderButtons(buttonItem['event'], orderItem)">{{ buttonItem.name }}</view>
								</block>
							</view>
						</view>
					</view>
				</block>
			</mescroll-uni>

			<u-popup v-model="pickVisible" mode="center" width="90%">
				<!-- <view class="pickup-box" ref="pickupRef">
					<view class="title">{{$zhTran('提货凭证')}}</view>
					<view class="desc flex m-b-20 col-top">
						<view class="info">
							<view class="m-b-20">{{$zhTran('团&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;长：')}}</view>
							<view>{{$zhTran('提货地址')}}：</view>
						</view>
						<view class="text">
							<view class="m-b-20">{{orderInfo.leader_name}}</view>
							<view>{{orderInfo.region_address}}</view>
						</view>
					</view>
					<view class="pickup-line"></view>
					<view class="flex row-center">
						<view class="m-t-20 qr-contain " :class="{ 'qr-contain--die': orderInfo.verification_status }">
							<image :src="options.qrcode" mode="widthFix"></image>
						</view>
					</view>
					<view class="m-t-30 qr-code flex row-center">{{$zhTran('提货码')}}：{{ orderInfo.pickup_code }}</view>
				</view> -->
				<ticket-poster ref="poster" :options="options" @success="handleSuccess" @complete="handleComplete" />
				<view class="pickup-btns flex row-between m-t-20">
					<view class="share" @click="saveImageToOther">{{$zhTran('转发好友')}}</view>
					<view class="saveImg" @click="saveImageToAlbum">{{$zhTran('点击保存到相册')}}</view>
				</view>
			</u-popup>
		</view>
		<view style="width: 100%;height: 1rpx;overflow: hidden;padding-top: 10rpx;">
			<tki-qrcode ref="qrcode" uni="px" :val="orderInfo.pickup_code" :size="118 * 2" :showLoading="false"
				@result="getQrCodeUrl" />
		</view>
		<loading-view v-show="loading"></loading-view>
	</view>
</template>


<script>
	import {
		apiCommunityGroupPurchaseOrderList
	} from '@/api/community_group_purchase'
	import OrderMixin from '@/mixins/community_group_purchase_order'
	import {
		PaymentStatusEnum
	} from '@/utils/enum'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";
	import ticketPoster from "@/bundle2/pages/community_group_purchase/poster/ticket_poster.vue";
	export default {
		name: 'CGPOrderList',
		mixins: [OrderMixin, MescrollMixin],
		components: {
			ticketPoster,
		},

		data() {
			return {
				// Tabs列表
				tabsList: [{
					sign: 'all',
					name: this.$zhTran('全部'),
					list: [],
				}, {
					sign: 'pay',
					name: this.$zhTran('待付款'),
					list: [],
				}, {
					sign: 'delivery',
					name: this.$zhTran('待发货'),
					list: [],
				}, {
					sign: 'verification',
					name: this.$zhTran('待核销'),
					list: [],
				}, {
					sign: 'finish',
					name: this.$zhTran('已完成'),
					list: [],
				}, {
					sign: 'close',
					name: this.$zhTran('已关闭'),
					list: [],
				}],
				tabsIndex: '', // Tabs索引

				// 订单状态
				orderStatus: {
					0: {
						name: this.$zhTran('待付款'),
						style: 'primary',
					},
					1: {
						name: this.$zhTran('待发货'),
						style: 'primary',
					},
					2: {
						name: this.$zhTran('待核销'),
						style: 'primary',
					},
					3: {
						name: this.$zhTran('已完成'),
						style: 'muted',
					},
					4: {
						name: this.$zhTran('已关闭'),
						style: 'muted',
					}
				},

				price_symbol: '￥',
				pickVisible: false,
				options: {},
				imgPath: '',
				loading: false,
				orderInfo: {}
			}
		},

		computed: {
			// 当前Tab项
			currentTab() {
				return this.tabsList[this.tabsIndex] || {}
			},

			// 映射Tabs项
			mapTabsItem() {
				return sign => this.tabsList.find(item => item['sign'] === sign)
			}
		},

		methods: {
			// 更改当前Tab页
			changeCurrentTab(index) {
				this.tabsIndex = index
				this.refreshOrderData()
			},

			// 刷新订单数据 @Mixins【/src/mixins/order.js】内调用，请勿删除
			refreshOrderData() {
				this.$nextTick(() => {
					this.mescroll.resetUpScroll()
				})
			},

			// 上拉加载更多
			upCallback({
				num,
				size
			}) {
				const sign = this.currentTab.sign
				apiCommunityGroupPurchaseOrderList({
					type: sign,
					page_no: num,
					page_size: size,
				}).then(({
					lists,
					page_size,
					count,
					extend
				}) => {
					const tab = this.mapTabsItem(sign)
					lists.forEach(item => item['buttons'] = this.getOrderStatusButtons(item.btn) ?? [])
					if (num === 1) tab.list = []
					tab.list = [...tab.list, ...lists]
					tab.list = this.$zhTran(tab.list)
					this.price_symbol = extend.price_symbol
					this.mescroll.endSuccess(lists.length, count)
				}).catch(err => {
					this.mescroll.endErr()
				})
			},

			// 去订单详情
			goOrderDetail(id) {
				this.$Router.push({
					path: '/bundle2/pages/community_group_purchase/order/order_detail',
					query: {
						order_id: id
					}
				})
			},
			// 处理：查看提货码
			handlePickup(row) {
				this.loading = true
				this.orderInfo = this.$zhTran(row)
				this.$nextTick(function() {
					this.getPoster()
					this.pickVisible = true
				});
			},
			getPoster() {
				this.$nextTick(function() {
					const refQR = this.$refs["qrcode"];
					refQR._makeCode();
				});
				this.$refs.poster.drawCanvas();
			},
			getQrCodeUrl(val) {
				this.options = {
					name: this.orderInfo.leader_name,
					region_address: this.orderInfo.region_address,
					qrcode: val,
					pickup_code: this.orderInfo.pickup_code
				}
				console.log('options', this.options)
			},
			handleSuccess(val) {
				console.log('handleSuccess', this.imgPath)
				this.imgPath = val;
				this.loading = false
			},
			handleComplete() {
				console.log('handleComplete')
				this.loading = false
			},
			saveImageToOther() {
				console.log('imgPath', this.imgPath)
				uni.showShareImageMenu({
					path: this.imgPath
				})
			},
			saveImageToAlbum() {
				// #ifndef H5
				uni.saveImageToPhotosAlbum({
					filePath: this.imgPath,
					success: (res) => {
						this.$toast({
							title: this.$zhTran("保存成功"),
						});
					},
					fail: (err) => {
						this.$toast({
							title: this.$zhTran("保存失败"),
						});
					},
				});
				// #endif
				// #ifdef H5
				this.$toast({
					title: this.$zhTran("请长按图片保存"),
				});
				// #endif
			},
		},

		onLoad() {
			const options = this.$Route.query
			const mode = options.mode ?? 'all'
			const tabIndex = this.tabsList.findIndex(item => item['sign'] === mode)

			this.changeCurrentTab(tabIndex)
			setTimeout(() => {}, 0.5 * 1000)

			// 监听全局duringPayment事件
			uni.$on('duringPayment', ({
				result
			}) => {
				if (result === PaymentStatusEnum['SUCCESS']) {
					this.$Router.back()
					setTimeout(() => {
						this.$toast({
							title: this.$zhTran('支付成功')
						})
					}, 0.5 * 1000)
					this.refreshOrderData()
				}
			})
		},
		onUnload() {
			uni.$off('duringPayment')
		},
	}
</script>


<style lang="scss">
	page {
		height: 100%;
		padding: 0;
	}

	.order-list {
		height: 100%;
		display: flex;
		flex-direction: column;

		.order-item {
			flex: 1;
			min-height: 0;
		}
	}

	.order-contain {
		padding: 0 20rpx;
	}

	.order {
		padding-left: 20rpx;
		margin-top: 20rpx;
		border-radius: 5px;
		background-color: #FFFFFF;

		&-header {
			display: flex;
			height: 80rpx;
			align-items: center;
			padding-right: 20rpx;
			border-bottom: $-solid-border;

			.order-tag {
				padding: 4rpx 10rpx;
				margin-right: 10rpx;
				border-radius: 2px;
				font-size: $-font-size-xxs;
				color: #FFFFFF;

				&--pink {
					background: linear-gradient(#ff369a 0%, #ff2c3c 100%);
				}

				&--red {
					background: linear-gradient(#f95f2f 0%, #ff2c3c 100%);
				}

				&--blue {
					background: linear-gradient(#fa6aa9 0%, #fc00bb 100%);
				}

				&--green {
					background: linear-gradient(#0cc21e 0%, #06c160 100%);
				}
			}

			.order-sn {
				font-size: $-font-size-nr;
			}

			.order-status {
				margin-left: auto;
				font-size: $-font-size-sm;

				&--primary {
					color: rgba(250, 64, 52, 1);
				}

				&--muted {
					color: $-color-muted;
				}
			}
		}

		&-main {
			.order-desc {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				padding: 20rpx;
				font-size: $-font-size-xs;
				color: $-color-muted;
			}
		}

		&-footer {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100rpx;
			padding-right: 20rpx;
			border-top: $-solid-border;

			.order-button {
				box-sizing: border-box;
				padding: 10rpx 30rpx;
				border-radius: 2px;
				font-size: $-font-size-nr;

				&:nth-child(n+2) {
					margin-left: 20rpx;
				}

				&--primary {
					background-color: rgba(255, 208, 0, 1);
					color: rgba(74, 25, 0, 1);
				}

				&--normal {
					border-width: 1px;
					border-style: solid;
					@include border_color() @include font_color()
				}

				&--muted {
					border: $-solid-border;
					color: $-color-lighter;
				}
			}
		}

	}


	.pickup-box {
		padding: 30rpx;
		background-color: rgba(255, 255, 255, 1);
		border-radius: 10rpx;

		.title {
			color: rgba(56, 56, 56, 1);
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}

		.info {
			color: rgba(150, 150, 150, 1);
			font-size: 26rpx;
			width: 180rpx;
			text-align: justify;
		}

		.text {
			color: rgba(56, 56, 56, 1);
			font-size: 26rpx;
		}

		.pickup-line {
			margin: 30rpx 0;
			width: 100%;
			height: 1rpx;
			border: 1rpx dashed rgba(226, 226, 226, 1);
		}

		.qr-contain {
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			align-items: center;
			width: 140px;
			height: 140px;
			border: 1px solid #cccccc;
			border-radius: 5px;

			&--die {
				position: relative;

				&::before {
					position: absolute;
					z-index: 99;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					display: block;
					content: "";
					background-color: rgba(255, 255, 255, 0.5);
				}
			}

		}
	}

	.pickup-btns {
		&>view {
			width: calc((100% - 30rpx) / 2);
			font-size: 26rpx;
			color: rgba(34, 34, 34, 1);
			border-radius: 10rpx;
			padding: 20rpx 0;
			background-color: rgba(255, 255, 255, 1);
			text-align: center;
		}

		.saveImg {
			background-color: rgba(255, 208, 0, 1);
		}
	}
</style>